<?php
namespace submodule\controllers;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;


use submodule\models\Models;
use submodule\models\ModelsField;
use common\components\Tree;
use base\YiiMobo;

use \common\models\DIYModel;

class ModelsFormController extends \submodule\base\BaseSubmoduleController
{

    public $categorys;
	
	public $uid;
	
	public $model;
	
	public $model_data;
	
	public $data;
	
	public $models;//模型参数配置

	public $allowinput_fields;//允许后台录入的字段
	
	public $fields;//模型字段
	
	public $modelid;
	
	public $tablename;
	public $data_tablename;
	
	public $default_field = array('id', 'modelid', 'addtime', 'updatetime', 'listorder');
	
	
	
	
	public function init(){
		
		parent::init();
		$this->modelid = $_REQUEST['modelid'];
		$this->models = Yii::$app->FileCache->get('backend_models_'.$this->modelid);
		//print_r($this->models['models']);exit;
		$this->allowinput_fields = $this->models['allowinput_fields'];
		$this->fields = $this->models['fields'];
		//$this->models['models'] = $this->models['models']['models'];
		$this->tablename = '{{%'.$this->models['models']['tablename'].'}}';
		
		$this->data_tablename = '{{%'.$this->models['models']['tablename'].'_data}}';
		
		
		
		
	}
	/**
	 * @return array action filters
	 */
	public function filters() {
     return array( 
        array('auth.filters.AuthFilter'),
            );
        }


	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate($parentid = 0)
	{
		//print_r($this->fields);exit;
		$sql='select * from '.$this->tablename.' where id=0';
	
		$model = Yii::$app->getDb()->getTableSchema($this->tablename);
		$model =  (object)null;
		foreach (Yii::$app->getDb()->getTableSchema($this->tablename)->columns as $column) {
            $value = $column->defaultValue ? $column->defaultValue : '';
            $model->{$column->name} = $value;
			$model->attributes[$column->name] = $value;
            
        }
		
		if($this->models['models']['type'] == 'content'){
			foreach (Yii::$app->getDb()->getTableSchema($this->data_tablename)->columns as $column) {
				$value = $column->defaultValue ? $column->defaultValue : '';
				$model->{$column->name} = $value;
				$model->attributes[$column->name] = $value;
				
			}
		}else if($this->models['models']['type'] == 'category'){
			$model->parentid = $model->attributes['parentid'] = $parentid;
		}
        if(isset($_POST['Models']))
		{
			$this->SaveForm();
		}
		$this->data['id'] = '';
		foreach($this->fields as $k=>$v){
		    $this->data[$v['field']] = isset($setting['defaultvalue']) ? $setting['defaultvalue'] : '';
		}
		//print_r($this->data);exit;
		return $this->render('modelsform_form',[
		    'model'=> $model,
		    
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
			'allowinput_fields'=> $this->allowinput_fields
		]);
	}
	
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionUpdate($id)
	{
		
		
		
        if(isset($_POST['Models']))
		{
			$this->SaveForm($id);
		}else{
			
		}
		
		$sql="SELECT * FROM $this->tablename a";
		if($this->models['models']['type'] == 'content') $sql .= " inner join $this->data_tablename b on a.id = b.id";
		$sql .= " where a.id = $id";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if (!$data){
            $this->OperTips(['backurl'=> '', 'error'=> true, 'title'=> '数据不存在', 'timeout'=> 3000]);
		}
		$model = (object)$data;
		$model->attributes = $data;

		return $this->render('modelsform_form',[
		    'model'=> $model,
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
		]);
	}

	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionView($id)
	{
		$sql="SELECT * FROM $this->tablename a";
		if($this->models['models']['type'] == 'content') $sql .= " inner join $this->data_tablename b on a.id = b.id";
		$sql .= " where a.id = $id";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if (!$data) $this->null_OperTips();
		$model = $data;
		
        $viewfile = "modelsform_{$this->models['models']['type']}_view";
        //print_r($this->fields);exit;
		return $this->render($viewfile,[
		    'model'=> $model,
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
		]);
	}

	/**
	 * 保存表单提交数据
     * 
	 */
	public function SaveForm($id = ''){
		$tableName = $this->models['models']['tablename'];
		$class = 'submodule_'.$tableName;
		$sFile = "../runtime/submodule_save/$class.php";
		require($sFile);
		$save = new $class($this->models, $_POST['Models'], $this->modelid);
		$data = [];
		$data_data = [];
		foreach($this->fields as $k=>$v){
			if ($v['field'] != 'id'){
				$defaultvalue = isset($v['setting']['defaultvalue']) ? $v['setting']['defaultvalue'] : NULL;
				if (!$v['allowinput']){
                    $value = $defaultvalue;
				}else{
				    $value = isset($_POST['Models'][$v['field']]) ? $_POST['Models'][$v['field']] : $defaultvalue;
			    }
				if ($v['formtype'] == 'checkbox'){
					$value = $value ? $this->jsons_encode($value) : '';
				}
			    
				if (method_exists($save, $v['field'].'_save')){
					$savefunction = $v['field'].'_save';
					$value = $save->$savefunction($v['fieldid'], $v['field']);
				}
				if($v['primarytable']){
                    $data[$v['field']] = $value;
				}else{
					$data_data[$v['field']] = $value;
				}
			}
		}
		//$data['modelid'] = $this->modelid; 
		$data['updatetime'] = time(); 
		if (!$id){
			$data['addtime'] = time(); 
		}else{
            unset($data['addtime']);
		}
		$connection = Yii::$app->db;
        $connection->open();
		//print_r($data);exit;
		
		//update
		if ($id){
			$insertid = $id;
			$connection->createCommand()->update($this->tablename, $data, 'id = '.$id)->execute();
			if($this->models['models']['type'] == 'content'){
				$connection->createCommand()->update($this->data_tablename, $data_data, 'id = '.$id)->execute();
			}
		//insert
		}else{
		    $connection->createCommand()->insert($this->tablename, $data)->execute();
			$insertid = $data_data['id'] = $connection->getLastInsertID();
			if($this->models['models']['type'] == 'content'){
				$connection->createCommand()->insert($this->data_tablename, $data_data)->execute();
			}
		}


		try{
			if($this->models['models']['type'] == 'category'){
				$depth = $this->CategoryDepth($insertid);
			    $connection->createCommand()->update($this->tablename, ['depth'=> join(',', $depth)], 'id = '.$insertid)->execute();
			    $children = $this->CategoryChildren($insertid);
			    $connection->createCommand()->update($this->tablename, ['children'=> $children], 'id = '.$insertid)->execute();
				$this->updateCategoryCache();
			}
			$data['backurl'] = $this->createUrl(['models-form/index', 'modelid'=>$this->modelid]);
			if(Yii::$app->request->getIsAjax()){
				
				$this->echojson($data);
			}else{
			    $this->OperTips($data['backurl']);
			}
		}catch (Exception $e){
			var_dump($e);
		}
	}
		
		
	public function Save($data, $savefunction){
		$function = create_function('$a','
			    $this = $data[$k];
			    $savefunction
			');
		
	}
		/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionIndex(){
		if ($this->models['models']['type'] == 'category'){
			$this->actionIndexCategory();
			
		}else if ($this->models['models']['type'] == 'content'){
		    $this->actionIndexContent();	
		}else{
		    $this->actionIndexContent();	
		}
	}
	
	public function actionIndexContent(){
		$search = [];
		$search['keyword'] = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : NULL;
        $search['starttime'] = isset($_REQUEST['starttime']) ? $_REQUEST['starttime'] : NULL;
        $search['endtime'] = isset($_REQUEST['endtime']) ? $_REQUEST['endtime'] : NULL;


		$indexFields = $this->indexFields();
        $fields = ['a.`id`'];
        foreach($indexFields as $k=>$v){
            $fields[] = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';    
        }
        $fields = join(', ',$fields);
		$sql = "SELECT $fields FROM $this->tablename a";
		if (strpos($fields,'b.`')){
            $sql .= " inner join $this->data_tablename b on a.`id` = b.`id`";
		}
		$sql .= ' where 1 = 1';
		if ($search['keyword']){
			foreach($this->fields as $v){
				if (isset($v['setting']['search']) && $v['setting']['search']){
					$field = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';
					$sql .= " and $field like '%".$search['keyword']."%'";
				}
			}
		}
		if ($search['starttime']) $sql .= " and a.`addtime` >= ".strtotime($search['starttime']);
		if ($search['endtime']) $sql .= " and a.`addtime` <= ".strtotime($search['endtime']);

        
        $orderby = isset($_REQUEST['orderby']) ? $_REQUEST['orderby'] : "a.`id` desc";
        $sql .= ' order by '.$orderby;
        $views = @$this->models['models']['setting']['index']['views'];
		$viewfile = $views ? $views : "modelsform_{$this->models['models']['type']}_index";
		echo $this->render($viewfile, array_merge(YiiMobo::pageRows($sql), [
		    'search'=>$search,
		    'orderby' => explode(' ',$orderby),
		    'models' => $this->models,
			'modelid' => $this->modelid,
			'indexFields' => $this->indexFields()
		]));
		
	}
	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/city/index.php
	 */
	public function actionIndexCategory(){
		$parentid = 0;
		$ajax = 1 ;
		$tr = '';
		$str = '';
		if (intval($this->models['models']['setting']['index']['ajax']) == 0){
			$list = Yii::$app->FileCache->get("models_data_".$this->modelid);	
			if(!$list){
				$list = $this->updateCategoryCache(true);
			}
			$tree = new Tree();
			$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
			$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
			if ($list) foreach($list as $k=>$r) {
				$list[$k]['str_manage'] = '<a href="'.$this->createUrl(['models-form/update','id'=>$r['id'], 'modelid'=>$this->modelid]).'" title="编辑" class="operation-update"> </a>&nbsp;&nbsp;<a href="'.$this->createUrl(['models-form/delete','id'=>$r['id'], 'modelid'=>$this->modelid]).'" title="删除" class="operation-delete"> </a>';
				$url = $this->createUrl(['models-form/status', 'locked'=>'-locked-', 'id'=>$r['id'], 'modelid'=>$this->modelid]);
				$list[$k]['display_button'] = '<div onclick="change_switch(this, \''.$url.'\');" id="btn-locked" class="locked-'.intval($r['status']).'"></div>';
				
				$list[$k]['click_img'] = '<img class="click_img" id="click_'.$r['id'].'" src="'.dirname(Yii::getAlias('@web')).'/static/common/images/left_e.gif'.'">&nbsp;&nbsp;';
				foreach($this->indexFields() as $kk=>$val){
					if ($val['field'] == 'addtime' || $val['field'] == 'updatetime'){
						$list[$k][$val['field']] = date('Y-m-d', $r[$val['field']]);
					}
				}
			}

			$ajax = 0;
			$str .= "<td align='center' width='20'><input type='checkbox' value='\$id' name='checked_id[]'/></td>";
			foreach($this->indexFields() as $k=>$val){
				if ($val['field'] == 'listorder'){
					$str .= "<td align='center'><input name='listorder[\$id]' type='text' size='3' value='\$listorder' class='input-text input-listorder'></td>";
				}else if ($val['field'] == 'name'){
					$str .= "<td >\$spacer<input name='name[\$id]' type='text' style='width:150px' value='\$name' class='input-text input-name'></td>"; 
				}else	if ($val['field'] == 'status'){
					$str .= "<td class='td-locked'>\$display_button</td>";
				}else{
					$str .= "<td >\${$val['field']}</td>"; 
				}
			}
			$str .= "<td align='center'  class='td-operation'>\$str_manage</td>";
			$str .= "</tr>";
			$tree->init($list);
            $tr = $tree->get_tree(0,$str, $parentid);
		}
		
		
		

		$views = @$this->models['models']['setting']['index']['views'];
		$viewsfile = $views ? $views : ($ajax ? "modelsform_{$this->models['models']['type']}_index-ajax" : "modelsform_{$this->models['models']['type']}_index");
		echo $this->render($viewsfile, [
		    'models' => $this->models,
            'tr'=>$tr,
			'modelid' => $this->modelid,
			'indexFields' => $this->indexFields()
			
		]);
		
	}
	
	public function actionGetData($modelid, $parentid = 0){
		$sql="SELECT * FROM $this->tablename where parentid = $parentid order by listorder asc,id asc";
		$data['modelid'] = $modelid;
		$data['data'] = Yii::$app->db->createCommand($sql)->queryAll();
		$data['depth'] = $this->CategoryDepth($parentid);
		$data['count'] = count($data['data']) - 1;
		foreach($data as $k=>$v){
			
			//$data[$k]['depth'] = $this->CategoryDepth($v['id']);
		    	
		}
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	
	public function CategoryDepth($myid, &$newarr = []){
		//global $newarr;
		$sql="SELECT parentid FROM $this->tablename where id = $myid";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if(!$data){
			//$newarr = [];
			 return false;
		}
		$parentid = $data['parentid'];
        $newarr[] = $parentid;
		
		if($parentid){
		    $this->CategoryDepth($parentid, $newarr);
		}
        
		return array_reverse($newarr);
	}
	public function CategoryChildren($myid){
		$sql="SELECT id FROM $this->tablename where FIND_IN_SET('$myid', depth)";
		return (int)Yii::$app->db->createCommand($sql)->queryAll();
	}

	public function actionDelete($modelid, $id){
		if ($this->models['models']['type'] == 'category'){
			$sql="SELECT id FROM $this->tablename where parentid = $id";
			if(Yii::$app->db->createCommand($sql)->queryOne()){
				$this->OperTips(['backurl'=> '', 'error'=> true, 'title'=> '不能删除有子级分类的数据', 'timeout'=> 3000]);
			}
			
		}else if ($this->models['models']['type'] == 'content'){
			$return = Yii::$app->db->createCommand()->delete($this->data_tablename, 'id = '.$id)->execute();
		}
		    $return = Yii::$app->db->createCommand()->delete($this->tablename, 'id = '.$id)->execute();
		if ($this->models['models']['type'] == 'category'){	
			$this->updateCategoryCache();
		}
		
		$this->OperTips();
	}
    /**
     * 更改状态设置
     * 
     */
    public function actionStatus($id, $field = 'status', $status) {
        $sql = "update $this->tablename set `$field` = $status where id = '$id'";
        Yii::$app->db->createCommand($sql)->query();
		$this->updateCategoryCache();
    }
	
	/**
	* 更新分类数据缓存
	*
	*/
    public function updateCategoryCache($return = false){
    	if ($this->models['models']['type'] != 'category') return false;
        if (intval($this->models['models']['setting']['index']['ajax']) == 0){
			$sql="SELECT * FROM $this->tablename order by listorder asc, id desc";
			$data = Yii::$app->db->createCommand($sql)->queryAll();
			
			$array = array();
			foreach($data as $k=>$v){
				$depth = $this->CategoryDepth($v['id']);
				
				$v['depth'] = $depth;
				$array[$v['id']] = $v;
				Yii::$app->db->createCommand()->update($this->tablename, ['depth'=>join(',', $depth)], 'id = '.$v['id'])->execute();
				
			}
			Yii::$app->FileCache->set("models_data_".$this->modelid, $array);
			if ($return) return $array;
		}
	}
	
	public function formFields(){
		foreach($this->fields as $v){
			if (!in_array($v['field'], $this->default_field)){
				$data[] = $v;
			}
		}
		return $data;
		
	}
	
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch(){
        $ids = isset($_POST['checked_id']) ? $_POST['checked_id'] : NULL;
        if(isset($_POST['batch_delete']) && $ids){
            if (isset($_POST['batch_delete'])){
                if ($this->models['models']['type'] == 'content'){
					Yii::$app->db->createCommand()->delete($this->tablename, ['id'=>$ids])->execute();
					$return = Yii::$app->db->createCommand()->delete($this->data_tablename, ['id'=>$ids])->execute();
				}else if ($this->models['models']['type'] == 'category'){
					$catid = [];
					foreach($ids as $id){
						$sql="SELECT id FROM $this->tablename where parentid = $id";
						if(!Yii::$app->db->createCommand($sql)->queryOne()){
							$catid[] = $id;
						}
					}
					Yii::$app->db->createCommand()->delete($this->tablename, ['id'=>$catid])->execute();
				}
		        
		
            }
			
        }else if(isset($_POST['batch_listorder'])){
			if ($_POST['listorder']) foreach($_POST['listorder'] as $id=>$listorder){
				if (is_numeric($id)){
					$data = [
						'name' => $_POST['name'][$id],
						'listorder'=>intval($listorder),
					
					];
					Yii::$app->db->createCommand()->update($this->tablename, $data, 'id = '.$id)->execute();
				}
			}
		}else if(isset($_POST['batch_create'])){
			if(isset($_POST['add_ame'])) foreach($_POST['add_ame'] as $k=>$v){
				if (!$v) continue;
				$data = [
				    'name' => $v,
					'parentid' => $_POST['add_pid'][$k],
					'listorder' => $_POST['add_listorder'][$k],
				];
				Yii::$app->db->createCommand()->insert($this->tablename, $data)->execute();
				$insertid = Yii::$app->db->getLastInsertID();
				if($this->models['models']['type'] == 'category'){
					$depth = $this->CategoryDepth($insertid);
					Yii::$app->db->createCommand()->update($this->tablename, ['depth'=> join(',', $depth)], 'id = '.$insertid)->execute();	
					//exit($depth);				
				}
			}
		}
		
        if ($this->models['models']['type'] == 'category'){	
			$this->updateCategoryCache();
		}
		
		$this->OperTips();
	}
	
	public function indexFields(){
		$fields = array();
		foreach($this->models['models']['setting']['index']['listorder'] as $k=>$val){
			if(isset($this->fields[$val]) && in_array($this->fields[$val]['field'], $this->models['models']['setting']['index']['fields'])){
				$value = $this->fields[$val];
				//$value['_values'] = 
				$fields[$val] = $value;
			}
		}
		return $fields;
	}
	
	
	public function listorderFields(){
	    
	    $fields = array_diff($this->fields, $this->models['models']['setting']['index']['listorder']);
		
	}
	

	


}
